package com.cicadasmall.security;

import com.cicadasmall.common.base.LoginUser;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.data.domain.UserDO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * LoginUserDetails
 *
 * @author Jin
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(callSuper = true)
public class LoginUserDetails extends UserDO implements LoginUser, UserDetails {

    private static final long serialVersionUID = 4125096758372084669L;


    @JsonIgnore
    private Set<String> roleKeys;

    @JsonIgnore
    private Set<Integer> roleIds;

    @JsonIgnore
    private Set<String> dataScopes;

    @JsonIgnore
    private Set<String> permissions;

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> collection = new HashSet<>();
        if (Fn.isNotEmpty(roleKeys)) {
            roleKeys.parallelStream().forEach(roleKey -> collection.add(new SimpleGrantedAuthority("ROLE_" + roleKey)));
        }
        if (Fn.isNotEmpty(permissions)) {
            permissions.parallelStream().forEach(permission -> collection.add(new SimpleGrantedAuthority(permission)));
        }
        return collection;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public Set<Integer> getRoleIds() {
        return roleIds;
    }

    @Override
    public Set<String> getDataScopes() {
        return dataScopes;
    }
}
